class Logger {
  constructor() {
    this.storageKey = 'app_logs'
    this.maxLogEntries = 1000 // 限制日志条目数量
  }

  getStoredLogs(type) {
    const logs = localStorage.getItem(this.storageKey)
    const allLogs = logs ? JSON.parse(logs) : []
    const retLogs = []
    for(let i = 0; i < allLogs.length; i++) {
      
      if(allLogs[i].message.data.operation === type) {
        // allLogs[i].message.data = JSON.parse(allLogs[i].message.data)
        retLogs.push(allLogs[i])
      }
    }
    // console.log('retLogs', retLogs)
    return retLogs
    // if (type) {
    //   console.log('allLogs', allLogs[0]) // Add this line to print allLogs t
    //   return allLogs.filter(log => log.message.operation === type)
    // }
    // return allLogs
  }

  setStoredLogs(logs) {
    // 只保留最新的日志条目
    const trimmedLogs = logs.slice(-this.maxLogEntries)
    localStorage.setItem(this.storageKey, JSON.stringify(trimmedLogs))
  }

  formatMessage(type, message) {
    const timestamp = new Date().toISOString()
    return {
      timestamp,
      type,
      message
    }
  }

  log(type, message) {
    try {
      const logs = this.getStoredLogs()
      const logEntry = this.formatMessage(type, message)
      logs.push(logEntry)
      this.setStoredLogs(logs)
    } catch (error) {
      console.error('Error writing to log storage:', error)
    }
  }

  logRequest(requestData) {
    this.log('REQUEST', {
      url: requestData.url,
      method: requestData.method,
      data: requestData.data,
      timestamp: new Date().toISOString()
    })
  }

  logResponse(responseData) {
    this.log('RESPONSE', {
      status: responseData.status,
      data: responseData.data,
      timestamp: new Date().toISOString()
    })
  }

  logError(error) {
    this.log('ERROR', {
      message: error.message,
      stack: error.stack,
      timestamp: new Date().toISOString()
    })
  }

  // 清除所有日志
  clearLogs() {
    localStorage.removeItem(this.storageKey)
  }
}

export const logger = new Logger()